<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import Request from '@/api/axios'
import { UserAddOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { safeJsonParse } from '@/utils/safeJson'
import AddFriendModal from '@/views/chat/components/AddFriendModal.vue'
import { formatTime } from '@/utils/formatTime'
const userStore = useUserStore()
const { id } = storeToRefs(userStore)

const target_user_id = ref()
const sendMsg = ref('')
const respond = ref<any>('')
const record = ref<any>([])
const menuList = ref<any[]>([])
const activeIndex = ref<any>()
const chat_window_show = ref(false)
const addFriendVisible = ref(false)

import WebSocketUtility from '@/api/ws'
import { ChatMessageType, type ChatMessage } from '@/views/chat/types'
const isSecure = window.location.protocol === 'https:';
const wsProtocol = isSecure ? 'wss://' : 'ws://';

const ws = new WebSocketUtility(
    `${wsProtocol}${window.location.host}/ws/chat?id=${id.value}`,
    (msg) => {
        respond.value = safeJsonParse(msg).value
        if (respond.value.SenderID == id.value && respond.value.ReceiverID != id.value) {
            if (respond.value.Status == true) {
                message.success('对方接收')
            } else message.info('对方不在线')
        }
        record.value.push(respond.value)
    },
    (err) => {
        message.error('WebSocket 异常')
        console.log(err)
    },
    () => {
        message.error('连接关闭')
    },
    () => {
        console.log('连接开启')
    },
    () => {
        console.log('heartbeat')
    },
    30 * 1000
)

onMounted(async () => {
    await Request.get({ url: `/user/friend` })
        .then((res) => {
            menuList.value = res.info
        })
})
const handleScrollToBottom = () => {
    const el = document.getElementById('scrollContainer') as HTMLElement
    setTimeout(() => {
        el.scrollTo({
            top: el.scrollHeight,
            behavior: 'smooth'
        })
    }, 200)
}
const SendMessage = () => {
    if (sendMsg.value.toString().trim() === '') {
        message.warning('消息不能为空')
        return
    }
    const msg: ChatMessage = {
        timestamp: -1,
        sender: `${id.value}`,
        receiver: target_user_id.value.toString(),
        text: sendMsg.value.toString(),
        type: ChatMessageType.PrivateMessage
    }
    ws.send(JSON.stringify(msg))
    sendMsg.value = ''
}

const GetChatRecord = () => {
    record.value = []
    Request.get({
        url: `/chat/record?id=${menuList.value[activeIndex.value].id}`
    }).then((respond) => {
        respond.info ??= []
        record.value = respond.info.sort(
            (a, b) => new Date(a.CreatedAt).getTime() - new Date(b.CreatedAt).getTime()
        )
    })
}



const getFriendAvatar = (friendId: number) => {
    return `https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png`
}

const getFriendStatus = (friendId: number) => {
    return 'online'
}
</script>

<template>
    <div class="chat-container">
        <div class="friends-list">
            <div class="friends-header">
                <h2>好友列表</h2>
                <a-button type="link" @click="addFriendVisible = true">
                    <template #icon>
                        <UserAddOutlined />
                    </template>
                </a-button>
            </div>
            <div class="friends-items">
                <div v-for="(item, index) in menuList" :key="index" class="friend-item"
                    :class="{ active: activeIndex === index }" @click="() => {
                        target_user_id = item.id
                        activeIndex = index
                        chat_window_show = true
                        GetChatRecord()
                        nextTick(handleScrollToBottom)
                    }">
                    <div class="avatar-container">
                        <img :src="item.avatar || getFriendAvatar(item.id)" class="avatar" />
                        <div class="online-indicator" :class="{ online: getFriendStatus(item.id) === 'online' }"></div>
                    </div>
                    <div class="friend-info">
                        <span class="friend-name">{{ item.username }}</span>
                        <span class="friend-status" :class="{ online: getFriendStatus(item.id) === 'online' }">
                            {{ getFriendStatus(item.id) === 'online' ? '在线' : '离线' }}
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="chat_window_show" class="chat-area">
            <div class="chat-header">
                <div class="chat-with">
                    <div class="avatar-container">
                        <img :src="menuList[activeIndex]?.avatar || getFriendAvatar(target_user_id)"
                            @click="$router.push({ name: 'profile', query: { uid: target_user_id } })" class="avatar"
                            style="cursor: pointer;" />
                        <div class="online-indicator" :class="{ online: getFriendStatus(target_user_id) === 'online' }">
                        </div>
                    </div>
                    <div>
                        <h3>{{ menuList[activeIndex]?.username }}</h3>
                        <p :class="{ online: getFriendStatus(target_user_id) === 'online' }">
                            {{ getFriendStatus(target_user_id) === 'online' ? '在线' : '离线' }}
                        </p>
                    </div>
                </div>
            </div>

            <div class="messages-container" id="scrollContainer">
                <div v-for="(item, index) in record" :key="index" class="message"
                    :class="{ 'message-me': item.SenderID === id, 'message-other': item.SenderID !== id }">
                    <div class="message-content">
                        <p>{{ item.Content || item.text }}</p>
                        <span class="message-time">{{ formatTime(item.CreatedAt || item.timestamp) }}</span>
                    </div>
                </div>
            </div>

            <div class="message-input">
                <input v-model="sendMsg" @keyup.enter="SendMessage" placeholder="输入消息..." class="input-field" />
                <button @click="SendMessage" class="send-button">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                        stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="22" y1="2" x2="11" y2="13"></line>
                        <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                    </svg>
                </button>
            </div>
        </div>
    </div>

    <AddFriendModal :id="id" :visible="addFriendVisible" @update:visible="($event) => { addFriendVisible = $event }" />
</template>

<style scoped>
.chat-container {
    display: flex;
    height: 90vh;
    background-color: var(--bg-color);
    color: var(--text-color);
}

.friends-list {
    width: 300px;
    border-right: 1px solid var(--border-color);
    display: flex;
    flex-direction: column;
    background-color: var(--bg-secondary);
}

.friends-header {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.friends-header h2 {
    margin: 0;
    font-size: 1.2rem;
}

.friends-items {
    flex: 1;
    overflow-y: auto;
}

.friend-item {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    cursor: pointer;
    transition: background-color 0.2s;
    border-bottom: 1px solid var(--border-color);
}

.friend-item:hover {
    background-color: rgba(255, 255, 255, 0.05);
}

.friend-item.active {
    background-color: rgba(74, 107, 255, 0.1);
}

.avatar-container {
    position: relative;
    margin-right: 15px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    cursor: pointer;
}

.online-indicator {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #9e9e9e;
    border: 2px solid var(--bg-secondary);
}

.online-indicator.online {
    background-color: var(--online-color);
}

.friend-info {
    display: flex;
    flex-direction: column;
}

.friend-name {
    font-weight: 500;
    margin-bottom: 3px;
}

.friend-status {
    font-size: 0.8rem;
    color: #9e9e9e;
}

.friend-status.online {
    color: var(--online-color);
}

.chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.chat-header {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
}

.chat-with {
    display: flex;
    align-items: center;
}

.chat-with h3 {
    margin: 0 0 5px 0;
}

.chat-with p {
    margin: 0;
    font-size: 0.9rem;
    color: #9e9e9e;
}

.chat-with p.online {
    color: var(--online-color);
}

.messages-container {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background-color: var(--bg-color);
}

.message {
    display: flex;
    margin-bottom: 20px;
}

.message-me {
    justify-content: flex-end;
}

.message-other {
    justify-content: flex-start;
}

.message-content {
    max-width: 60%;
    position: relative;
    display: flex;
    flex-direction: column;
}

.message-content p {
    margin: 0;
    padding: 12px 16px;
    border-radius: 18px;
    word-break: break-word;
    line-height: 1.4;
}

.message-me .message-content p {
    background-color: var(--primary-color);
    color: white;
    border-top-right-radius: 4px;
}

.message-other .message-content p {
    background-color: var(--message-bg-other);
    border-top-left-radius: 4px;
}

.message-time {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    padding: 0 4px;
}

.message-me .message-time {
    text-align: right;
}

.message-other .message-time {
    text-align: left;
}

.message-input {
    padding: 15px;
    border-top: 1px solid var(--border-color);
    background-color: var(--bg-secondary);
    display: flex;
    gap: 10px;
}

.input-field {
    flex: 1;
    padding: 12px 15px;
    border-radius: 20px;
    border: 1px solid var(--border-color);
    background-color: var(--bg-color);
    color: var(--text-color);
    outline: none;
}

.send-button {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background-color: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background-color 0.2s;
}

.send-button:hover {
    background-color: var(--primary-hover);
}
</style>
